<?php

namespace app\controller\api;

use app\model\api\skzy\SkzyCamp;
use app\model\api\skzy\SkzyPool;
use app\model\api\skzy\SkzyRole;
use app\model\api\skzy\SkzySlave;
use app\service\ConfServiceFacade;
use laytp\controller\Api;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Facade;

/**
 * Class Skzy
 * @package app\index\controller
 */
class Skzy extends Api
{
    public function getPoolName()
    {
        $list = (new SkzyPool())->cache(true)->column("id,name,pool_type");
        return $this->success("success", $list);
    }

    public function getPoolDetail()
    {
        $data = input('post.');
        $model = new SkzySlave();
        if (!isset($data['id']) || $data['id'] == '') {
            return $this->error("请选择卡池");
        }
        $detail = (new SkzyPool())->cache(true)->field('name,pool_type,role_relation_id,slave_relation_id,up_id')->where("id", $data['id'])->find();
        if (!$detail) {
            return $this->error("卡池不存在");
        }
        $detail = $detail->toArray();
        $camp = (new SkzyCamp())->cache(true)->column('name,icon,picture,english_name', 'id');
        foreach ($camp as &$item){
            $item['icon'] = imgUrlToAbsolute($item['icon']);
            $item['picture'] = imgUrlToAbsolute($item['picture']);
        }
        $detail['role_relation_id'] = json_decode($detail['role_relation_id'], true);
        $detail['slave_relation_id'] = json_decode($detail['slave_relation_id'], true);
        if ($detail['pool_type'] == 'normal' || $detail['pool_type'] == 'role') {
            array_push($detail['role_relation_id'], $detail['up_id']);
        }
        $master_data = [];
        if (is_array($detail['role_relation_id'])&& count($detail['role_relation_id']) > 0) {
            $role_data = (new SkzyRole())->cache(true)->whereIn('id', $detail['role_relation_id'])
                ->field('id,camp_id,name,level,icon,picture')->select()->toArray();
            foreach ($role_data as &$item) {
                $item['icon'] = imgUrlToAbsolute($item['icon']);
                $item['picture'] = imgUrlToAbsolute($item['picture']);
                $item['camp_info'] = $camp[$item['camp_id']];
                if ($item['id'] == $detail['up_id']) {
                    $item['up'] = true;
                }
            }
            $master_data = array_merge($master_data, $role_data);
        }
        $slave = [];
        if (is_array($detail['slave_relation_id']) && count($detail['slave_relation_id']) > 0) {
            $slave = $model->cache(true)->whereIn('id', $detail['slave_relation_id'])
                ->field('id,camp_id,name,level,icon,picture')->select()->toArray();
            foreach ($slave as &$item) {
                $item['icon'] = imgUrlToAbsolute($item['icon']);
                $item['picture'] = imgUrlToAbsolute($item['picture']);
                $item['camp_info'] = $camp[$item['camp_id']];
            }
        }
        switch ($detail['pool_type']) {
            case "normal":
            case "role":
            $temp = $model->where('level', 3)->field('id,camp_id,name,level,icon,picture')->select()->toArray();
                foreach ($temp as &$item) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                    $item['picture'] = imgUrlToAbsolute($item['picture']);
                    $item['camp_info'] = $camp[$item['camp_id']];
                }
                $slave = array_merge($slave,$temp);
                break;
            case "slave":
                $temp = $model->whereIn('level', [3,4])->field('id,camp_id,name,level,icon,picture')->select()->toArray();
                foreach ($temp as &$item) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                    $item['picture'] = imgUrlToAbsolute($item['picture']);
                    $item['camp_info'] = $camp[$item['camp_id']];
                }
                $slave = array_merge($slave,$temp);
                break;
        }
        //处理master_data 数据
        $S = [];
        $A = [];
        $B = [];
        foreach ($master_data as $value){
            switch ($value['level']){
                case 5:
                    $S[] = $value;
                    break;
                case 4:
                    $A[] = $value;
                    break;
                case 3:
                    $B[] = $value;
                    break;
            }
        }
        return $this->success("success", compact('S','A','B','slave'));
    }

    public function uploadFile(){
        $data = input("post.");
        if(!isset($data['image'])){
            return api_error("请上传图片");
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $data['image'], $res)) {
            //获取图片类型
            $type = $res[2];
            //图片名字
            $fileName = md5(time()) . '.' . $type;
            if (!file_exists("./temp_image/")) {
                mkdir(iconv("UTF-8", "GBK", "./temp_image/"),0777,true);
            }
            // 临时文件
            $tmpfname = "./temp_image/".$fileName;
            //保存图片
            $handle = fopen($tmpfname, "w");
            $ossConf = [
                'accessKeyID' => ConfServiceFacade::get('aliOss.accessKeyID'),
                'accessKeySecret' => ConfServiceFacade::get('aliOss.accessKeySecret'),
                'bucket' => ConfServiceFacade::get('aliOss.bucket'),
                'endpoint' => ConfServiceFacade::get('aliOss.endpoint'),
                'domain' => ConfServiceFacade::get('aliOss.domain'),
            ];
            $object = "xm_game/skzy/".date("Ymd") . "/" . md5(uniqid(mt_rand())) . ".png";
            if (fwrite($handle, base64_decode(str_replace($res[1], '', $data['image']))))
            {
                $oss = new OssClient($ossConf['accessKeyID'],$ossConf['accessKeySecret'],$ossConf['endpoint']);
                try {
                    $ossUploadRes = $oss->uploadFile($ossConf['bucket'], $object, $tmpfname);
                    if ($ossUploadRes) {
                        if (!isset($ossUploadRes['info']['url'])) {
                            return api_error('保存失败');
                        }
                        $inputValue = $ossUploadRes['info']['url'];
                        $filePath = $inputValue;
                        //删除临时图片
                        unlink($tmpfname);
                        return api_success(['url'=>$filePath]);
                    }
                }catch (OssException $e){
                    return api_error($e->getMessage());
                }
            }
        }else{
            return api_error("图片格式错误");
        }
    }
}